package map;

import org.junit.Test;

import java.util.*;

/**
 * @Auther ljn
 * @Date 2019/12/20
 * 将map的key和value分别转化为list
 */
public class mapToList {
    public static void main(String[] args) {

        Map<String,String> map = new HashMap<>();
        map.put("1", "A");
        map.put("2", "B");
        map.put("3", "C");
        map.put("4", "D");
        map.put("5", "E");

        /* map.keySet()返回的是Set */
        List<String> keylist = new ArrayList<>(map.keySet());
        keylist.sort(Comparator.reverseOrder());
        for(String key:keylist){
            System.out.println(key);
        }


        /* map.values()返回的是collection，通过arrayList的构造方法可以实现 */
        List<String> valuesList = new ArrayList<>(map.values());
        for (String s : valuesList) {
            System.out.println(s);
        }
    }

    /**
     * 1.computeIfAbsent 如果key不存在就会帮你放进去并生成value并返回
     * 2.computeIfAbsent 如果key存在就直接返回value就好咯
     */
    @Test
    public void test02(){
        Map<String, List<String>> map = new HashMap<>();
        map.computeIfAbsent("a", keyName->{
            return new ArrayList<>();
        }).add("value1");

        map.computeIfAbsent("a", keyName ->{
            return new ArrayList<>();
        }).add("value2");
        System.out.println(map.get("a"));
    }

    @Test
    public void test03() {
        HashMap<String, String> serviceCode = new HashMap<String, String>() {
            {
                put("OB", "OS");
                put("OJ", "OE");
            }
        };
        serviceCode.forEach((k,v)->{
            System.out.println(k);
            System.out.println(v);
        });
    }

    @Test
    public void test04(){
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "apple");
        map.put(2, "banana");
        map.put(3, "orange");

        System.out.println("Map containsKey 1: " + map.containsKey(1));
        System.out.println("Map containsKey 4: " + map.containsKey(4));
    }
}
